package com.gurumades.jsonform.server.forms.dispatch;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.gurumades.jsonform.shared.dispatch.validators.CoreFormItemValidators;
import com.gurumades.jsonform.shared.dispatch.validators.FormItemValidator;


public class FormPreprocessHelpImpl extends FormPreprocessHelp {
	 
	protected Map<String,Set<FormItemValidator>> itemScopeValidators = new HashMap<String,Set<FormItemValidator>>();
	protected Set<FormValidator> formScopeValidators = new HashSet<FormValidator>();
	protected Set<FormSubmiter> formSubmitors = new HashSet<FormSubmiter>();
	
	HashMap<String, Serializable> buildParams = new HashMap<String, Serializable>();
	
	
	public FormPreprocessHelpImpl() {
		addFormItemValidator("*", new CoreFormItemValidators());
	}
	
	@Override
	public void addSubmitHandler(FormSubmiter fs) {
		formSubmitors.add(fs);
	}
	
	@Override
	public void addFormValidator(FormValidator fs) {
		formScopeValidators.add(fs);
	}
	
	@Override
	public void addFormItemValidator(String itemID, FormItemValidator fs) {
		Set<FormItemValidator> validators = itemScopeValidators.get(itemID);
		if (validators == null) {
			validators = new HashSet<FormItemValidator>();
			itemScopeValidators.put(itemID, validators);
		}
		
		validators.add(fs);
	}
	
	@Override
	public Set<FormValidator> getFormValidators() {
		return formScopeValidators;
	}
	
	@Override
	public Set<FormItemValidator> getItemValidators(String itemID) {
		Set<FormItemValidator> theSet = itemScopeValidators.get(itemID);
		if (theSet == null) {
			theSet = new HashSet<FormItemValidator>();
		}
		theSet.addAll(itemScopeValidators.get("*"));
		
		return theSet;
	}

	public static void cache(Long buildID, FormPreprocessHelp build){
		FormBuildCache.cache(buildID, build);
	}
	
	public static FormPreprocessHelp get(Long buildID){
		return FormBuildCache.get(buildID);
	}


	@Override
	public Collection<String> getItemValidators() {
		Set<String> strs = itemScopeValidators.keySet();
		return strs;
	}

	@Override
	public Set<FormSubmiter> getSubmiters() {
		return formSubmitors;
	}

	@Override
	public void setBuildParams(HashMap<String, Serializable> buildParams) {
		this.buildParams = buildParams;
	}
	
	@Override
	public HashMap<String, Serializable> getBuildParams() {
		return buildParams;
	}
}
